package com.ruoyi.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PreDestroy;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author CHN
 * @since 2024-04-07 16:01
 */
@Configuration
public class AsyncConfig {

    public static final ThreadPoolTaskExecutor ASYNC_TASK_EXECUTOR = new ThreadPoolTaskExecutor();

    public static final ExecutorService VIRTUAL_EXECUTOR = Executors.newVirtualThreadPerTaskExecutor();

    private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class);

    static {
        final int availableProcessors = Runtime.getRuntime().availableProcessors();
        ASYNC_TASK_EXECUTOR.setCorePoolSize(availableProcessors * 10);
        ASYNC_TASK_EXECUTOR.setMaxPoolSize(availableProcessors * 20);
        ASYNC_TASK_EXECUTOR.setQueueCapacity(availableProcessors * 100);
        ASYNC_TASK_EXECUTOR.setThreadNamePrefix("Application-Async-");
        ASYNC_TASK_EXECUTOR.initialize();
    }

    @Bean
    @Primary
    public AsyncTaskExecutor asyncTaskExecutor() {
        return ASYNC_TASK_EXECUTOR;
    }

    @PreDestroy
    public void closeExecutorService() {
        ASYNC_TASK_EXECUTOR.shutdown();
        VIRTUAL_EXECUTOR.shutdown();
    }
}
